package com.xuyu.nacos.callback.listener.analysekey;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Objects;

/**
 * @author xuyu
 * 不用关心类型，自动按照传入参数的类型去匹配对应的key值解析器
 */
@Component
@Slf4j
public class KeyFactory {


    private final List<AbstractGetKey<?>> allKeyAnalyser;

    public KeyFactory(List<AbstractGetKey<?>> allKeyAnalyser) {
        this.allKeyAnalyser = allKeyAnalyser;
    }

    /**
     * 这个方法通用解析对应的key值出来
     * @param o 参数
     * @return 返回值
     */
    public String analyse(Object o) {
        if (allKeyAnalyser == null || allKeyAnalyser.isEmpty()) {
            throw new RuntimeException("nacos变更解析器加载失败");
        }
        for (AbstractGetKey analyser : allKeyAnalyser) {
            try {
                //获得解析器的泛型类型
                ParameterizedType genericSuperclass = (ParameterizedType)analyser.getClass().getGenericSuperclass();
                Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
                if (actualTypeArguments.length != 1 || !Objects.equals(actualTypeArguments[0].getTypeName(), o.getClass().getName())) {
                    continue;
                }
                String key = analyser.analyseKey(o);
                if (key != null && !key.isEmpty()) {
                    return key;
                }
            } catch (Exception e) {
                log.error("异常信息", e);
            }
        }
        return null;
    }

}
